<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="~{common/base :: layout(~{::title}, ~{::content}, ~{::style}, ~{::script})}">
<head>
    <title>用户管理 - 后台管理系统</title>
    <style th:fragment="style">
        .dashboard-card {
            border-radius: 8px;
            box-shadow: 0 3px 5px rgba(0, 0, 0, 0.05);
            transition: all 0.3s;
            overflow: hidden;
            height: 100%;
        }
        .dashboard-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
        }
        .stat-card {
            border: none;
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        .stat-card:hover {
            transform: translateY(-3px);
        }
        .stat-icon {
            font-size: 1.5rem;
            margin-bottom: 0.25rem;
        }
        .stat-value {
            font-size: 1.5rem;
            font-weight: bold;
            margin: 0;
        }
        .status-badge {
            border-radius: 30px;
            padding: 0.4rem 0.8rem;
            font-weight: 500;
            min-width: 100px;
            text-align: center;
        }
        .role-badge {
            border-radius: 30px;
            padding: 0.4rem 0.8rem;
            font-weight: 500;
            min-width: 100px;
            text-align: center;
        }
        .filter-btn {
            border-radius: 20px;
            margin: 0 0.25rem;
            padding: 0.4rem 0.75rem;
            font-weight: 500;
            font-size: 0.9rem;
        }
        .table-hover tbody tr:hover {
            background-color: rgba(13, 110, 253, 0.05);
        }
        .action-btn {
            border-radius: 20px;
            padding: 0.25rem 0.75rem;
        }
        .search-form label {
            font-weight: 500;
            color: #495057;
        }
        .pagination .page-item .page-link {
            border-radius: 5px;
            margin: 0 2px;
        }
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(255, 255, 255, 0.8);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        .loading-spinner {
            width: 3rem;
            height: 3rem;
        }
        .content-wrapper {
            max-width: 1400px;
            margin: 0 auto;
            padding: 1.5rem;
        }
        /* 修复点击问题 */
        .stretched-link::after {
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            z-index: 1;
            content: "";
        }
        .search-card {
            border-bottom: 1px solid rgba(0,0,0,0.1);
            margin-bottom: 0;
            border-bottom-left-radius: 0;
            border-bottom-right-radius: 0;
        }
        .list-container {
            min-height: 300px;
            position: relative;
        }
        .list-loading {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(255, 255, 255, 0.7);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 10;
        }
        .avatar-sm {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
        }
        .gender-icon {
            width: 20px;
            height: 20px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            margin-right: 0.25rem;
        }
    </style>
</head>
<body>
    <div th:fragment="content">
        <div class="content-wrapper">
            <!-- 页面标题 -->
            <div class="bg-light p-3 mb-4 dashboard-card">
                <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center">
                    <h2 class="mb-3 mb-md-0 fs-4">用户管理</h2>
                </div>
            </div>

            <!-- 用户统计卡片 -->
            <div class="row g-3 mb-4" th:if="${userStats != null}">
                <div class="col-6 col-md-3">
                    <div class="stat-card bg-primary bg-opacity-10 dashboard-card position-relative">
                        <div class="stat-icon text-primary">
                            <i class="bi bi-people"></i>
                        </div>
                        <h6 class="text-muted mb-1 small">总用户数</h6>
                        <p class="stat-value text-primary mb-0" th:text="${userStats[0]}">0</p>
                    </div>
                </div>
                <div class="col-6 col-md-3">
                    <div class="stat-card bg-danger bg-opacity-10 dashboard-card position-relative">
                        <div class="stat-icon text-danger">
                            <i class="bi bi-shield-lock"></i>
                        </div>
                        <h6 class="text-muted mb-1 small">管理员</h6>
                        <p class="stat-value text-danger mb-0" th:text="${userStats[1]}">0</p>
                    </div>
                </div>
                <div class="col-6 col-md-3">
                    <div class="stat-card bg-success bg-opacity-10 dashboard-card position-relative">
                        <div class="stat-icon text-success">
                            <i class="bi bi-person-check"></i>
                        </div>
                        <h6 class="text-muted mb-1 small">正常用户</h6>
                        <p class="stat-value text-success mb-0" th:text="${userStats[2]}">0</p>
                    </div>
                </div>
                <div class="col-6 col-md-3">
                    <div class="stat-card bg-secondary bg-opacity-10 dashboard-card position-relative">
                        <div class="stat-icon text-secondary">
                            <i class="bi bi-person-slash"></i>
                        </div>
                        <h6 class="text-muted mb-1 small">禁用用户</h6>
                        <p class="stat-value text-secondary mb-0" th:text="${userStats[3]}">0</p>
                    </div>
                </div>
            </div>

            <!-- 用户列表和搜索 -->
            <div class="dashboard-card mb-4">
                <!-- 搜索区域 -->
                <div class="bg-white p-3 border-0 search-card">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0 fs-5"><i class="bi bi-search me-2 text-primary"></i>用户搜索</h5>
                    </div>
                    <form id="searchForm" class="row g-3" method="get" action="/admin/users">
                        <div class="col-md-10">
                            <label class="form-label">关键词</label>
                            <div class="input-group">
                                <span class="input-group-text bg-white">
                                    <i class="bi bi-search"></i>
                                </span>
                                <input type="text" class="form-control" name="keyword" id="keywordInput" th:value="${keyword}" placeholder="用户名/昵称/手机号/邮箱">
                            </div>
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <div class="d-grid gap-2 w-100">
                                <div class="btn-group">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="bi bi-search me-1"></i>搜索
                                    </button>
                                    <button type="button" id="resetBtn" class="btn btn-outline-secondary">
                                        <i class="bi bi-arrow-repeat me-1"></i>重置
                                    </button>
                                </div>
                            </div>
                        </div>
                        <input type="hidden" name="pageNum" id="pageNumInput" value="1">
                        <input type="hidden" name="pageSize" id="pageSizeInput" th:value="${userPage != null ? userPage.size : 10}">
                    </form>
                </div>
                
                <!-- 用户列表区域 -->
                <div class="card-header bg-white p-3 border-0">
                    <h5 class="mb-0 fs-5"><i class="bi bi-list-ul me-2 text-primary"></i>用户列表</h5>
                </div>
                <div class="card-body p-0 list-container">
                    <!-- 加载中指示器 -->
                    <div class="list-loading" id="listLoading">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                    </div>
                    
                    <div id="userListContainer">
                        <div th:if="${userPage != null && !userPage.records.empty}">
                            <div class="table-responsive">
                                <table class="table table-hover align-middle mb-0">
                                    <thead class="table-light">
                                        <tr>
                                            <th class="ps-3">用户</th>
                                            <th>用户名</th>
                                            <th>联系方式</th>
                                            <th>状态</th>
                                            <th>角色</th>
                                            <th>注册时间</th>
                                            <th>最后登录</th>
                                            <th class="pe-3">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr th:each="user : ${userPage.records}">
                                            <td class="ps-3">
                                                <div class="d-flex align-items-center">
                                                    <img th:if="${user.avatar != null}" th:src="${user.avatar}" alt="Avatar" class="avatar-sm me-2">
                                                    <div th:if="${user.avatar == null}" class="avatar-sm me-2 bg-light d-flex align-items-center justify-content-center rounded-circle">
                                                        <i class="bi bi-person text-secondary"></i>
                                                    </div>
                                                    <div>
                                                        <div class="fw-bold" th:text="${user.nickname ?: '未设置昵称'}">用户昵称</div>
                                                        <small class="text-muted">
                                                            <span th:if="${user.gender == 1}" class="gender-icon bg-primary bg-opacity-10"><i class="bi bi-gender-male text-primary"></i></span>
                                                            <span th:if="${user.gender == 2}" class="gender-icon bg-danger bg-opacity-10"><i class="bi bi-gender-female text-danger"></i></span>
                                                            <span th:if="${user.gender == 0}" class="gender-icon bg-secondary bg-opacity-10"><i class="bi bi-question text-secondary"></i></span>
                                                            ID: <span th:text="${user.id}">1</span>
                                                        </small>
                                                    </div>
                                                </div>
                                            </td>
                                            <td th:text="${user.username}">username</td>
                                            <td>
                                                <div th:if="${user.phone != null}"><i class="bi bi-phone me-1"></i><span th:text="${user.phone}">13800138000</span></div>
                                                <div th:if="${user.email != null}"><i class="bi bi-envelope me-1"></i><span th:text="${user.email}">user@example.com</span></div>
                                            </td>
                                            <td>
                                                <span th:class="${user.status == 1 ? 'status-badge bg-success' : 'status-badge bg-secondary'}"
                                                      th:text="${user.status == 1 ? '正常' : '禁用'}">
                                                    用户状态
                                                </span>
                                            </td>
                                            <td>
                                                <span th:class="${user.role == 1 ? 'role-badge bg-danger' : 'role-badge bg-primary'}"
                                                      th:text="${user.role == 1 ? '管理员' : '普通用户'}">
                                                    用户角色
                                                </span>
                                            </td>
                                            <td th:text="${user.createTime != null ? #temporals.format(user.createTime, 'yyyy-MM-dd HH:mm:ss') : '未知'}">
                                                2025-06-08 12:00:00
                                            </td>
                                            <td th:text="${user.lastLoginTime != null ? #temporals.format(user.lastLoginTime, 'yyyy-MM-dd HH:mm:ss') : '未登录'}">
                                                2025-06-08 12:00:00
                                            </td>
                                            <td class="pe-3">
                                                <div class="d-flex">
                                                    <button th:if="${user.status == 1 && user.role != 1}" class="btn btn-sm btn-outline-secondary action-btn me-1 status-btn"
                                                            th:data-user-id="${user.id}" data-status="0">
                                                        <i class="bi bi-ban"></i> 禁用
                                                    </button>
                                                    <button th:if="${user.status == 0}" class="btn btn-sm btn-outline-success action-btn me-1 status-btn"
                                                            th:data-user-id="${user.id}" data-status="1">
                                                        <i class="bi bi-check-circle"></i> 启用
                                                    </button>
                                                    <button th:if="${user.role == 0}" class="btn btn-sm btn-outline-danger action-btn me-1 role-btn"
                                                            th:data-user-id="${user.id}" data-role="1">
                                                        <i class="bi bi-shield"></i> 设为管理员
                                                    </button>
                                                    <button th:if="${user.role == 1}" class="btn btn-sm btn-outline-primary action-btn me-1 role-btn"
                                                            th:data-user-id="${user.id}" data-role="0">
                                                        <i class="bi bi-person"></i> 设为普通用户
                                                    </button>
                                                    <button th:if="${user.role != 1}" class="btn btn-sm btn-outline-danger action-btn delete-btn"
                                                            th:data-user-id="${user.id}">
                                                        <i class="bi bi-trash"></i> 删除
                                                    </button>
                                                    <button class="btn btn-sm btn-outline-warning action-btn reset-pwd-btn"
                                                            th:data-user-id="${user.id}">
                                                        <i class="bi bi-key"></i> 重置密码
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- 分页 -->
                            <div th:if="${userPage.pages > 1}" class="d-flex flex-column flex-md-row justify-content-between align-items-center p-3 bg-light border-top">
                                <div class="mb-3 mb-md-0">
                                    <span class="text-secondary">显示 
                                        <span class="fw-bold" th:text="${(userPage.current-1) * userPage.size + 1}">1</span> 到 
                                        <span class="fw-bold" th:text="${userPage.current * userPage.size > userPage.total ? userPage.total : userPage.current * userPage.size}">10</span> 
                                        条，共 <span class="fw-bold" th:text="${userPage.total}">100</span> 条记录
                                    </span>
                                </div>
                                <div class="d-flex flex-column flex-md-row align-items-center">
                                    <select id="pageSizeSelector" class="form-select form-select-sm me-0 me-md-3 mb-3 mb-md-0" style="width: auto;">
                                        <option value="10" th:selected="${userPage.size == 10}">10条/页</option>
                                        <option value="20" th:selected="${userPage.size == 20}">20条/页</option>
                                        <option value="50" th:selected="${userPage.size == 50}">50条/页</option>
                                    </select>
                                    <ul class="pagination pagination-sm mb-0">
                                        <li class="page-item" th:classappend="${userPage.current == 1 ? 'disabled' : ''}">
                                            <a class="page-link page-nav" data-page="${userPage.current - 1}" href="javascript:void(0)" aria-label="Previous">
                                                <span aria-hidden="true">&laquo;</span>
                                            </a>
                                        </li>
                                        
                                        <!-- 动态分页导航 -->
                                        <th:block th:with="startPage=${T(Math).max(1, userPage.current - 2)}, endPage=${T(Math).min(userPage.pages, startPage + 4)}">
                                            <!-- 如果开始页大于1，显示第1页 -->
                                            <li class="page-item" th:if="${startPage > 1}">
                                                <a class="page-link page-nav" data-page="1" href="javascript:void(0)">1</a>
                                            </li>
                                            <!-- 如果开始页大于2，显示省略号 -->
                                            <li class="page-item disabled" th:if="${startPage > 2}">
                                                <span class="page-link">...</span>
                                            </li>
                                            
                                            <!-- 显示页码 -->
                                            <li class="page-item" th:each="num : ${#numbers.sequence(startPage, endPage)}"
                                                th:classappend="${num == userPage.current ? 'active' : ''}">
                                                <a class="page-link page-nav" th:data-page="${num}" href="javascript:void(0)" th:text="${num}">1</a>
                                            </li>
                                            
                                            <!-- 如果结束页小于总页数-1，显示省略号 -->
                                            <li class="page-item disabled" th:if="${endPage < userPage.pages - 1}">
                                                <span class="page-link">...</span>
                                            </li>
                                            <!-- 如果结束页小于总页数，显示最后一页 -->
                                            <li class="page-item" th:if="${endPage < userPage.pages}">
                                                <a class="page-link page-nav" th:data-page="${userPage.pages}" href="javascript:void(0)" th:text="${userPage.pages}">10</a>
                                            </li>
                                        </th:block>
                                        
                                        <li class="page-item" th:classappend="${userPage.current == userPage.pages ? 'disabled' : ''}">
                                            <a class="page-link page-nav" th:data-page="${userPage.current + 1}" href="javascript:void(0)" aria-label="Next">
                                                <span aria-hidden="true">&raquo;</span>
                                            </a>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 无用户提示 -->
                        <div th:if="${userPage == null || userPage.records.empty}" class="text-center py-5">
                            <i class="bi bi-people display-1 text-muted"></i>
                            <p class="mt-3 text-muted" th:text="${error != null ? error : '暂无用户记录'}">暂无用户记录</p>
                            <button id="refreshBtn" class="btn btn-outline-primary mt-2">
                                <i class="bi bi-arrow-repeat me-1"></i>刷新列表
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 确认模态框 -->
        <div class="modal fade" id="confirmModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content border-0 shadow">
                    <div class="modal-header">
                        <h5 class="modal-title" id="confirmModalTitle">确认操作</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body" id="confirmModalBody">
                        确定要执行此操作吗？
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" id="confirmBtn">确定</button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 加载动画 -->
        <div class="loading-overlay" id="loadingOverlay">
            <div class="spinner-border text-primary loading-spinner" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
        </div>
    </div>

    <script th:fragment="script">
        // 显示加载动画
        function showLoading() {
            const loadingOverlay = document.getElementById('loadingOverlay');
            if (loadingOverlay) {
                loadingOverlay.style.display = 'flex';
            }
        }
        
        // 隐藏加载动画
        function hideLoading() {
            const loadingOverlay = document.getElementById('loadingOverlay');
            if (loadingOverlay) {
                loadingOverlay.style.display = 'none';
            }
        }
        
        // 显示列表加载动画
        function showListLoading() {
            const listLoading = document.getElementById('listLoading');
            if (listLoading) {
                listLoading.style.display = 'flex';
            }
        }
        
        // 隐藏列表加载动画
        function hideListLoading() {
            const listLoading = document.getElementById('listLoading');
            if (listLoading) {
                listLoading.style.display = 'none';
            }
        }
        
        // 更新用户统计卡片
        function updateUserStats(stats) {
            if (!stats || !Array.isArray(stats)) return;
            
            // 更新各个统计的数量
            const statValues = document.querySelectorAll('.stat-value');
            if (statValues.length >= 4) {
                // 总用户数
                statValues[0].textContent = stats[0];
                
                // 管理员数
                statValues[1].textContent = stats[1];
                
                // 正常用户数
                statValues[2].textContent = stats[2];
                
                // 禁用用户数
                statValues[3].textContent = stats[3];
            }
        }
        
        // 显示提示消息
        function showToast(message, type) {
            let toastContainer = document.querySelector('.toast-container');
            if (!toastContainer) {
                toastContainer = document.createElement('div');
                toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
                toastContainer.style.zIndex = '1080';
                document.body.appendChild(toastContainer);
            }
            
            const toast = document.createElement('div');
            toast.className = `toast align-items-center text-white bg-${type} border-0`;
            toast.setAttribute('role', 'alert');
            toast.setAttribute('aria-live', 'assertive');
            toast.setAttribute('aria-atomic', 'true');
            
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">
                        <i class="bi bi-${type === 'success' ? 'check' : 'exclamation'}-circle me-2"></i>
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            `;
            
            toastContainer.appendChild(toast);
            const bsToast = new bootstrap.Toast(toast, {
                autohide: true,
                delay: 3000
            });
            bsToast.show();
            
            // 监听隐藏事件，移除DOM元素
            toast.addEventListener('hidden.bs.toast', function () {
                toast.remove();
            });
        }
        
        // 初始化确认模态框
        function initConfirmModal(title, message, callback) {
            const modal = document.getElementById('confirmModal');
            const modalTitle = document.getElementById('confirmModalTitle');
            const modalBody = document.getElementById('confirmModalBody');
            const confirmBtn = document.getElementById('confirmBtn');
            
            modalTitle.textContent = title;
            modalBody.textContent = message;
            
            // 移除之前的事件监听器
            const newConfirmBtn = confirmBtn.cloneNode(true);
            confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
            
            // 添加新的事件监听器
            newConfirmBtn.addEventListener('click', function() {
                callback();
                bootstrap.Modal.getInstance(modal).hide();
            });
            
            // 显示模态框
            const modalInstance = new bootstrap.Modal(modal);
            modalInstance.show();
        }

        // 更新用户状态
        function updateUserStatus(userId, status) {
            showLoading();
            $.ajax({
                url: '/admin/users/status',
                type: 'POST',
                data: { userId: userId, status: status },
                success: function(res) {
                    hideLoading();
                    if (res.code === 0) {
                        showToast(status === 1 ? '用户已启用' : '用户已禁用', 'success');
                        setTimeout(function() {
                            loadUserList();
                        }, 1000);
                    } else {
                        showToast(res.msg || '操作失败', 'danger');
                    }
                },
                error: function() {
                    hideLoading();
                    showToast('请求失败，请重试', 'danger');
                }
            });
        }

        // 更新用户角色
        function updateUserRole(userId, role) {
            showLoading();
            $.ajax({
                url: '/admin/users/role',
                type: 'POST',
                data: { userId: userId, role: role },
                success: function(res) {
                    hideLoading();
                    if (res.code === 0) {
                        showToast(role === 1 ? '已设置为管理员' : '已设置为普通用户', 'success');
                        setTimeout(function() {
                            loadUserList();
                        }, 1000);
                    } else {
                        showToast(res.msg || '操作失败', 'danger');
                    }
                },
                error: function() {
                    hideLoading();
                    showToast('请求失败，请重试', 'danger');
                }
            });
        }

        // 删除用户
        function deleteUser(userId) {
            showLoading();
            $.ajax({
                url: '/admin/users/delete',
                type: 'POST',
                data: { userId: userId },
                success: function(res) {
                    hideLoading();
                    if (res.code === 0) {
                        showToast('用户已删除', 'success');
                        setTimeout(function() {
                            loadUserList();
                        }, 1000);
                    } else {
                        showToast(res.msg || '删除失败', 'danger');
                    }
                },
                error: function() {
                    hideLoading();
                    showToast('请求失败，请重试', 'danger');
                }
            });
        }
        
        // 加载用户列表
        function loadUserList(page = 1) {
            showListLoading();
            
            // 获取搜索表单数据
            const keyword = $('#keywordInput').val();
            const pageSize = $('#pageSizeInput').val();
            
            // 更新页码
            $('#pageNumInput').val(page);
            
            // 构建请求参数
            const params = {
                pageNum: page,
                pageSize: pageSize
            };
            
            if (keyword) {
                params.keyword = keyword;
            }
            
            // 如果是重置操作，传递标志
            if (window.isResetOperation) {
                params.isReset = true;
                window.isResetOperation = false;
            }
            
            console.log('发送AJAX请求参数:', params);
            
            // 发送AJAX请求
            $.ajax({
                url: '/admin/users/ajax',
                type: 'GET',
                data: params,
                success: function(res) {
                    hideListLoading();
                    console.log('AJAX响应:', res);
                    
                    if (res.code === 0 && res.data) {
                        try {
                            // 从JSON数据生成HTML
                            const data = res.data;
                            const userPage = data.userPage;
                            
                            // 如果有统计数据且标记为全部统计，则更新统计卡片
                            if (data.userStats && data.isFullStats) {
                                updateUserStats(data.userStats);
                            }
                            
                            let html = '';
                            
                            if (userPage.records && userPage.records.length > 0) {
                                // 创建表格
                                html = `
                                    <div class="table-responsive">
                                        <table class="table table-hover align-middle mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th class="ps-3">用户</th>
                                                    <th>用户名</th>
                                                    <th>联系方式</th>
                                                    <th>状态</th>
                                                    <th>角色</th>
                                                    <th>注册时间</th>
                                                    <th>最后登录</th>
                                                    <th class="pe-3">操作</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                `;
                                
                                // 生成用户行
                                userPage.records.forEach(user => {
                                    // 格式化日期
                                    let createTime = '未知';
                                    if (user.createTime) {
                                        const date = new Date(user.createTime);
                                        createTime = date.toLocaleString('zh-CN', {
                                            year: 'numeric',
                                            month: '2-digit',
                                            day: '2-digit',
                                            hour: '2-digit',
                                            minute: '2-digit',
                                            second: '2-digit',
                                            hour12: false
                                        });
                                    }
                                    
                                    let lastLoginTime = '未登录';
                                    if (user.lastLoginTime) {
                                        const date = new Date(user.lastLoginTime);
                                        lastLoginTime = date.toLocaleString('zh-CN', {
                                            year: 'numeric',
                                            month: '2-digit',
                                            day: '2-digit',
                                            hour: '2-digit',
                                            minute: '2-digit',
                                            second: '2-digit',
                                            hour12: false
                                        });
                                    }
                                    
                                    // 添加行HTML
                                    html += `
                                        <tr>
                                            <td class="ps-3">
                                                <div class="d-flex align-items-center">
                                                    ${user.avatar ? 
                                                        `<img src="${user.avatar}" alt="Avatar" class="avatar-sm me-2">` : 
                                                        `<div class="avatar-sm me-2 bg-light d-flex align-items-center justify-content-center rounded-circle">
                                                            <i class="bi bi-person text-secondary"></i>
                                                        </div>`
                                                    }
                                                    <div>
                                                        <div class="fw-bold">${user.nickname || '未设置昵称'}</div>
                                                        <small class="text-muted">
                                                            ${user.gender === 1 ? 
                                                                '<span class="gender-icon bg-primary bg-opacity-10"><i class="bi bi-gender-male text-primary"></i></span>' : 
                                                                user.gender === 2 ? 
                                                                '<span class="gender-icon bg-danger bg-opacity-10"><i class="bi bi-gender-female text-danger"></i></span>' : 
                                                                '<span class="gender-icon bg-secondary bg-opacity-10"><i class="bi bi-question text-secondary"></i></span>'
                                                            }
                                                            ID: ${user.id}
                                                        </small>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>${user.username}</td>
                                            <td>
                                                ${user.phone ? `<div><i class="bi bi-phone me-1"></i>${user.phone}</div>` : ''}
                                                ${user.email ? `<div><i class="bi bi-envelope me-1"></i>${user.email}</div>` : ''}
                                            </td>
                                            <td>
                                                <span class="${user.status === 1 ? 'status-badge bg-success' : 'status-badge bg-secondary'}">
                                                    ${user.status === 1 ? '正常' : '禁用'}
                                                </span>
                                            </td>
                                            <td>
                                                <span class="${user.role === 1 ? 'role-badge bg-danger' : 'role-badge bg-primary'}">
                                                    ${user.role === 1 ? '管理员' : '普通用户'}
                                                </span>
                                            </td>
                                            <td>${createTime}</td>
                                            <td>${lastLoginTime}</td>
                                            <td class="pe-3">
                                                <div class="d-flex">
                                                    ${user.status === 1 && user.role !== 1 ? 
                                                        `<button class="btn btn-sm btn-outline-secondary action-btn me-1 status-btn"
                                                                 data-user-id="${user.id}" data-status="0">
                                                            <i class="bi bi-ban"></i> 禁用
                                                         </button>` : ''
                                                    }
                                                    ${user.status === 0 ? 
                                                        `<button class="btn btn-sm btn-outline-success action-btn me-1 status-btn"
                                                                 data-user-id="${user.id}" data-status="1">
                                                            <i class="bi bi-check-circle"></i> 启用
                                                         </button>` : ''
                                                    }
                                                    ${user.role === 0 ? 
                                                        `<button class="btn btn-sm btn-outline-danger action-btn me-1 role-btn"
                                                                 data-user-id="${user.id}" data-role="1">
                                                            <i class="bi bi-shield"></i> 设为管理员
                                                         </button>` : ''
                                                    }
                                                    ${user.role === 1 ? 
                                                        `<button class="btn btn-sm btn-outline-primary action-btn me-1 role-btn"
                                                                 data-user-id="${user.id}" data-role="0">
                                                            <i class="bi bi-person"></i> 设为普通用户
                                                         </button>` : ''
                                                    }
                                                    ${user.role !== 1 ? 
                                                        `<button class="btn btn-sm btn-outline-danger action-btn delete-btn"
                                                                 data-user-id="${user.id}">
                                                            <i class="bi bi-trash"></i> 删除
                                                         </button>` : ''
                                                    }
                                                    <button class="btn btn-sm btn-outline-warning action-btn reset-pwd-btn"
                                                             data-user-id="${user.id}">
                                                        <i class="bi bi-key"></i> 重置密码
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    `;
                                });
                                
                                html += `
                                            </tbody>
                                        </table>
                                    </div>
                                `;
                                
                                // 添加分页
                                if (userPage.pages > 1) {
                                    const startPage = Math.max(1, userPage.current - 2);
                                    const endPage = Math.min(userPage.pages, startPage + 4);
                                    
                                    html += `
                                        <div class="d-flex flex-column flex-md-row justify-content-between align-items-center p-3 bg-light border-top">
                                            <div class="mb-3 mb-md-0">
                                                <span class="text-secondary">显示 
                                                    <span class="fw-bold">${(userPage.current-1) * userPage.size + 1}</span> 到 
                                                    <span class="fw-bold">${Math.min(userPage.current * userPage.size, userPage.total)}</span> 
                                                    条，共 <span class="fw-bold">${userPage.total}</span> 条记录
                                                </span>
                                            </div>
                                            <div class="d-flex flex-column flex-md-row align-items-center">
                                                <select id="pageSizeSelector" class="form-select form-select-sm me-0 me-md-3 mb-3 mb-md-0" style="width: auto;">
                                                    <option value="10" ${userPage.size === 10 ? 'selected' : ''}>10条/页</option>
                                                    <option value="20" ${userPage.size === 20 ? 'selected' : ''}>20条/页</option>
                                                    <option value="50" ${userPage.size === 50 ? 'selected' : ''}>50条/页</option>
                                                </select>
                                                <ul class="pagination pagination-sm mb-0">
                                                    <li class="page-item ${userPage.current === 1 ? 'disabled' : ''}">
                                                        <a class="page-link page-nav" data-page="${userPage.current - 1}" href="javascript:void(0)" aria-label="Previous">
                                                            <span aria-hidden="true">&laquo;</span>
                                                        </a>
                                                    </li>
                                    `;
                                    
                                    // 显示第1页和省略号
                                    if (startPage > 1) {
                                        html += `
                                            <li class="page-item">
                                                <a class="page-link page-nav" data-page="1" href="javascript:void(0)">1</a>
                                            </li>
                                        `;
                                    }
                                    if (startPage > 2) {
                                        html += `
                                            <li class="page-item disabled">
                                                <span class="page-link">...</span>
                                            </li>
                                        `;
                                    }
                                    
                                    // 显示页码
                                    for (let i = startPage; i <= endPage; i++) {
                                        html += `
                                            <li class="page-item ${i === userPage.current ? 'active' : ''}">
                                                <a class="page-link page-nav" data-page="${i}" href="javascript:void(0)">${i}</a>
                                            </li>
                                        `;
                                    }
                                    
                                    // 显示省略号和最后一页
                                    if (endPage < userPage.pages - 1) {
                                        html += `
                                            <li class="page-item disabled">
                                                <span class="page-link">...</span>
                                            </li>
                                        `;
                                    }
                                    if (endPage < userPage.pages) {
                                        html += `
                                            <li class="page-item">
                                                <a class="page-link page-nav" data-page="${userPage.pages}" href="javascript:void(0)">${userPage.pages}</a>
                                            </li>
                                        `;
                                    }
                                    
                                    html += `
                                                    <li class="page-item ${userPage.current === userPage.pages ? 'disabled' : ''}">
                                                        <a class="page-link page-nav" data-page="${userPage.current + 1}" href="javascript:void(0)" aria-label="Next">
                                                            <span aria-hidden="true">&raquo;</span>
                                                        </a>
                                                    </li>
                                                </ul>
                                            </div>
                                        </div>
                                    `;
                                }
                            } else {
                                // 无用户记录
                                html = `
                                    <div class="text-center py-5">
                                        <i class="bi bi-people display-1 text-muted"></i>
                                        <p class="mt-3 text-muted">暂无用户记录</p>
                                        <button id="refreshBtn" class="btn btn-outline-primary mt-2">
                                            <i class="bi bi-arrow-repeat me-1"></i>刷新列表
                                        </button>
                                    </div>
                                `;
                            }
                            
                            // 更新列表内容
                            $('#userListContainer').html(html);
                            
                            // 重新绑定事件
                            bindEvents();
                            
                            // 更新总记录数
                            $('#totalRecords').html(`<i class="bi bi-people me-1"></i>共 ${userPage.total} 条记录`);
                            
                            // 更新URL，但不刷新页面
                            const url = new URL(window.location.href);
                            Object.keys(params).forEach(key => {
                                url.searchParams.set(key, params[key]);
                            });
                            window.history.pushState({}, '', url);
                        } catch (e) {
                            console.error('处理JSON数据出错:', e);
                            showToast('处理响应数据出错: ' + e.message, 'danger');
                            
                            // 显示错误信息
                            $('#userListContainer').html(`
                                <div class="text-center py-5">
                                    <i class="bi bi-exclamation-triangle display-1 text-warning"></i>
                                    <p class="mt-3 text-muted">处理数据出错</p>
                                    <p class="small text-danger">${e.message}</p>
                                    <button id="refreshBtn" class="btn btn-outline-primary mt-2">
                                        <i class="bi bi-arrow-repeat me-1"></i>刷新列表
                                    </button>
                                </div>
                            `);
                            
                            // 绑定刷新按钮
                            document.getElementById('refreshBtn').addEventListener('click', function() {
                                loadUserList(1);
                            });
                        }
                    } else {
                        // 显示错误消息
                        $('#userListContainer').html(`
                            <div class="text-center py-5">
                                <i class="bi bi-exclamation-triangle display-1 text-warning"></i>
                                <p class="mt-3 text-muted">${res.msg || '加载失败，请稍后再试'}</p>
                                <button id="refreshBtn" class="btn btn-outline-primary mt-2">
                                    <i class="bi bi-arrow-repeat me-1"></i>刷新列表
                                </button>
                            </div>
                        `);
                        
                        // 绑定刷新按钮
                        document.getElementById('refreshBtn').addEventListener('click', function() {
                            loadUserList(1);
                        });
                        
                        showToast(res.msg || '加载失败', 'danger');
                    }
                },
                error: function(xhr, status, error) {
                    hideListLoading();
                    console.error('AJAX请求失败:', status, error);
                    console.error('响应内容:', xhr.responseText);
                    
                    // 显示错误信息
                    $('#userListContainer').html(`
                        <div class="text-center py-5">
                            <i class="bi bi-exclamation-triangle display-1 text-warning"></i>
                            <p class="mt-3 text-muted">请求失败，服务器返回: ${xhr.status} ${xhr.statusText}</p>
                            <p class="small text-danger">${error || '未知错误'}</p>
                            <button id="refreshBtn" class="btn btn-outline-primary mt-2">
                                <i class="bi bi-arrow-repeat me-1"></i>刷新列表
                            </button>
                        </div>
                    `);
                    
                    // 绑定刷新按钮
                    document.getElementById('refreshBtn').addEventListener('click', function() {
                        loadUserList(1);
                    });
                    
                    showToast('请求失败，请重试', 'danger');
                }
            });
        }
        
        // 重置用户密码
        function resetUserPassword(userId) {
            showLoading();
            $.ajax({
                url: '/admin/users/reset-password',
                type: 'POST',
                data: { userId: userId },
                success: function(res) {
                    hideLoading();
                    if (res.code === 0) {
                        showToast('密码已重置为：123456', 'success');
                    } else {
                        showToast(res.msg || '重置密码失败', 'danger');
                    }
                },
                error: function() {
                    hideLoading();
                    showToast('请求失败，请重试', 'danger');
                }
            });
        }
        
        // 绑定事件函数
        function bindEvents() {
            // 初始化状态按钮
            document.querySelectorAll('.status-btn').forEach(function(button) {
                button.addEventListener('click', function() {
                    const userId = this.getAttribute('data-user-id');
                    const status = parseInt(this.getAttribute('data-status'));
                    initConfirmModal(
                        status === 1 ? '确认启用' : '确认禁用', 
                        status === 1 ? `确定要启用该用户吗？` : `确定要禁用该用户吗？`, 
                        function() {
                            updateUserStatus(userId, status);
                        }
                    );
                });
            });
            
            // 初始化角色按钮
            document.querySelectorAll('.role-btn').forEach(function(button) {
                button.addEventListener('click', function() {
                    const userId = this.getAttribute('data-user-id');
                    const role = parseInt(this.getAttribute('data-role'));
                    initConfirmModal(
                        role === 1 ? '设为管理员' : '设为普通用户', 
                        role === 1 ? `确定将该用户设置为管理员吗？` : `确定将该用户设置为普通用户吗？`, 
                        function() {
                            updateUserRole(userId, role);
                        }
                    );
                });
            });
            
            // 初始化删除按钮
            document.querySelectorAll('.delete-btn').forEach(function(button) {
                button.addEventListener('click', function() {
                    const userId = this.getAttribute('data-user-id');
                    initConfirmModal('确认删除', `确定要删除该用户吗？此操作不可恢复！`, function() {
                        deleteUser(userId);
                    });
                });
            });
            
            // 初始化重置密码按钮
            document.querySelectorAll('.reset-pwd-btn').forEach(function(button) {
                button.addEventListener('click', function() {
                    const userId = this.getAttribute('data-user-id');
                    initConfirmModal('重置密码', `确定要将该用户密码重置为123456吗？`, function() {
                        resetUserPassword(userId);
                    });
                });
            });
            
            // 初始化页面大小选择器
            const pageSizeSelector = document.getElementById('pageSizeSelector');
            if (pageSizeSelector) {
                pageSizeSelector.addEventListener('change', function() {
                    const pageSize = this.value;
                    $('#pageSizeInput').val(pageSize);
                    loadUserList(1); // 切换每页显示数量时重置为第1页
                });
            }
            
            // 为所有分页链接添加点击事件
            document.querySelectorAll('.page-nav').forEach(function(link) {
                link.addEventListener('click', function() {
                    if (!this.parentElement.classList.contains('disabled') && !this.parentElement.classList.contains('active')) {
                        const page = this.getAttribute('data-page');
                        if (page) {
                            loadUserList(parseInt(page));
                        }
                    }
                });
            });
            
            // 刷新按钮
            const refreshBtn = document.getElementById('refreshBtn');
            if (refreshBtn) {
                refreshBtn.addEventListener('click', function() {
                    loadUserList(1);
                });
            }
        }

        // 页面加载完成后初始化所有事件
        document.addEventListener('DOMContentLoaded', function() {
            // 隐藏加载动画
            hideLoading();
            hideListLoading();
            
            // 初始化重置按钮
            document.getElementById('resetBtn').addEventListener('click', function() {
                document.getElementById('keywordInput').value = '';
                // 设置一个标志，表示这是重置操作
                window.isResetOperation = true;
                loadUserList(1);
            });
            
            // 初始化搜索表单
            document.getElementById('searchForm').addEventListener('submit', function(e) {
                e.preventDefault(); // 阻止表单默认提交
                loadUserList(1);
            });
            
            // 初始化刷新按钮
            const refreshBtn = document.getElementById('refreshBtn');
            if (refreshBtn) {
                refreshBtn.addEventListener('click', function() {
                    loadUserList(1);
                });
            }
            
            // 绑定其他事件
            bindEvents();
        });
    </script>
</body>
</html> 